<template>
  <a-drawer
    title="选择关键词"
    width="736px"
    :visible="visible"
    @close="onClose"
    :zIndex="9999"
  >
    <div class="choose-keyword-wrapper">
      <div class="keyword-tip" v-if="is_tip">
        <div>选择的关键词将会用于 AI 文章创作，请注意</div>
        <ul class="mt-10 text-gray-400">
          <li>总关键词建议维持在 2 - 3 个，不要过多</li>
          <li>不同类目下相同的关键词只有一个会生效</li>
          <li>自行输入的关键词与选择的关键词总量建议为5个</li>
        </ul>
      </div>
      <div class="keyword-txt" v-if="!choose_tag.length">
        <div>请点击下方任意标签选择想用的关键词</div>
        <div class="my-10">再次点击同一个关键词可取消选择</div>
        <div style="color: #ff7b00">选择完标签后，请点击确定按钮</div>
      </div>
      <div class="choose-tags" v-else>
        <div class="mb-10 font-bold">已选择的关键词：</div>
        <a-tag
          style="margin-bottom: 5px"
          v-for="(tag, index) in choose_tag"
          color="blue"
          :key="tag"
          closable
          @close.stop="tagClose(index)"
          >{{ tag }}</a-tag
        >
        <div class="flex justify-end mt-10">
          <a-button size="small" type="primary" @click="onOk">确定</a-button>
        </div>
      </div>
      <div class="library-list">
        <a-collapse
          @change="changeLibrary"
          v-model:activeKey="current_collapsed_ids"
        >
          <a-collapse-panel :key="library.id" v-for="library in libraryList">
            <template #header>
              <div class="library-title">
                <span>{{ library.name }}</span>
                <div
                  @click.stop="
                    isDisabled(library.id) ? '' : allCheck(library.id)
                  "
                >
                  <a-checkbox
                    :disabled="isDisabled(library.id)"
                    :checked="hasCheckedAll(library.id)"
                  ></a-checkbox>
                  <span class="ml-5">全选</span>
                </div>
              </div>
            </template>
            <div class="tag-list">
              <a-tag
                v-for="(tag, index) in library_under_keyword[library.id]"
                :color="choose_tag.includes(tag) ? 'blue' : 'default'"
                @click="tagClick(tag)"
                :key="index"
                >{{ tag }}</a-tag
              >
            </div>
          </a-collapse-panel>
        </a-collapse>
      </div>
    </div>
  </a-drawer>
</template>
<script setup>
import { ref, reactive, watch } from "vue";
import { message } from "ant-design-vue";
import request from "@/common/utils/request";
import _ from "lodash";
const props = defineProps({
  visible: Boolean,
  onSuccess: Function,
  cancel: Function,
  tags: {
    type: Array,
    default: () => [],
  },
  is_tip: {
    type: Boolean,
    default: true,
  },
});

const emits = defineEmits(["cancel", "onSuccess"]);
// 当前正在打开的折叠面板
let current_collapsed_ids = ref([]);
// 已经打开过的折叠面板
let opened_collapsed_ids = ref([]);
let library_under_keyword = reactive({});
let current_library_id = ref("");
let choose_tag = ref([]);
let libraryList = ref([]);
let formRef = reactive({
  keyword_library_id: "",
  keyword: [],
});
let page = ref(1);
let pageSize = ref(50);
let total = ref(0);
const onClose = () => {
  emits("cancel");
};
const onOk = () => {
  emits("onSuccess", choose_tag.value);
};
const getLibraryList = () => {
  request
    .get("/work_ai", "/user/socialMedia/keywordLibrary/get", {})
    .then((res) => {
      libraryList.value = res.result;
      if (libraryList.value.length > 0) {
        if (!current_collapsed_ids.value.length) {
          current_collapsed_ids.value = [libraryList.value[0].id];
          getKeywordList(libraryList.value[0].id);
        }
      }
    });
};
const getKeywordList = (keyword_library_id) => {
  let params = {
    keyword_library_id,
  };
  request
    .get("/work_ai", "/user/socialMedia/keywordCollection/all", params)
    .then((res) => {
      library_under_keyword[keyword_library_id] = res.result;
    });
};
const allCheck = (id) => {
  hasCheckedAll(id) ? delCheck(id) : addCheck(id);
};
const delCheck = (id) => {
  choose_tag.value = choose_tag.value.filter((item) => {
    return !library_under_keyword[id].includes(item);
  });
};
const addCheck = (id) => {
  choose_tag.value.push(...library_under_keyword[id]);
};
const isDisabled = (id) => {
  return !library_under_keyword[id];
};
const hasCheckedAll = (id) => {
  if (!library_under_keyword[id]) {
    return false;
  } else {
    if (!library_under_keyword[id].length) {
      return false;
    }
    return library_under_keyword[id].every((item) => {
      return choose_tag.value.includes(item);
    });
  }
};
const changeLibrary = (keys) => {
  keys.forEach((key) => {
    if (!opened_collapsed_ids.value.includes(key)) {
      opened_collapsed_ids.value.push(key);
      getKeywordList(key);
    }
  });
};
const tagClick = (tag) => {
  if (choose_tag.value.includes(tag)) {
    choose_tag.value = choose_tag.value.filter((item) => item != tag);
  } else {
    if (choose_tag.value.length >= 20) {
      return message.warning("最多选择20个标签");
    }
    choose_tag.value.push(tag);
  }
};
const tagClose = (index) => {
  choose_tag.value.splice(index, 1);
};
const confirm = () => {};
watch(
  () => props.visible,
  (val) => {
    if (val) {
      let allTags = [];
      for (let key in library_under_keyword) {
        allTags.push(...library_under_keyword[key]);
      }
      let tagList = _.cloneDeep(props.tags);
      choose_tag.value = tagList.filter((item) => allTags.includes(item));
      getLibraryList();
    } else {
      formRef.keyword_library_id = "";
      formRef.keyword = [];
    }
  }
);
</script>
<style lang="less" scoped>
.text-gray-400 {
  color: #666;
}
.keyword-txt {
  margin-top: 20px;
  color: #999;
}
.library-list {
  margin-top: 20px;
}
.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  .ss-tag {
    cursor: pointer;
  }
}
.library-title {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
